#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity) {
        sort(buses.begin(), buses.end());
        sort(passengers.begin(), passengers.end());
        int pos = 0, c;
        for (int t : buses)
            for (c = capacity; c && pos < passengers.size() && passengers[pos] <= t; --c)
                ++pos;
        --pos;
        int ans = c ? buses.back() : passengers[pos];
        while (pos >= 0 && ans == passengers[pos])
        {
            --ans;
            --pos;
        }
        return ans;
    }
};